package com.erp.base.base;
 
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
 
@Transactional
public abstract class CrudService<D extends CrudDao<T,K>,T extends BaseEntity<T,K>,K> {
	/**
	 * 持久层对象
	 */
	@Autowired
	protected D dao;
	
	private int count=300;
	
	/**
	 * 获取单条数据
	 * @param id
	 * @return
	 */
	public T get(K id) {
		return dao.get(id);
	}
	
	/**
	 * 获取单条数据
	 * @param entity
	 * @return
	 */
	public T get(T entity) {
		return dao.get(entity);
	}
	
	/**
	 * 查询列表数据
	 * @param entity
	 * @return
	 */
	public List<T> findList(T entity) {
		return dao.findList(entity);
	}
	
	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param entity
	 * @return
	 */
	public Page<T> findPage(Page<T> page, T entity) {
		entity.setPage(page);
		page.setRows(dao.findList(entity));
		return page;
	}

	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void save(T entity) {
		if (entity.getIsNewRecord()){ 
			dao.insert(entity);
		}else{
			int i=dao.update(entity);
			if(i==0){
				throw new OptimisticLockingFailureException("乐观锁错误!") ;
			}
		}
	}//value="direwolf"
	
	/**
	 * 删除数据
	 * @param entity
	 */
	@Transactional(readOnly = false, propagation=Propagation.REQUIRED)
	public void delete(K id) {
		dao.delete(id);
	}
	
	
	/**
	 * 删除全部数据
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void deleteBatch(List<K> ids) {
		dao.deleteBatch(ids);
	} //value="direwolf",
	
	@Transactional(readOnly = false)
	public void insertBatch(List<T> list){
		if(list==null||list.isEmpty()){
			return;
		}else{
			int tmp=list.size()/count;
			for (int i = 0; i < tmp+1; i++) {
				if((i+1)*count<=list.size()){
					dao.insertBatch(list.subList(i*count, (i+1)*count));
				}else{
					dao.insertBatch(list.subList(i*count, list.size()));
				}
			}
		}
		
	}
}
